package DTask::Utils;
use 5.018;
use warnings;
use base 'Exporter';

our @EXPORT_OK = qw(wrapUATX wrapMongoDBOp wrapMangoOp renderJsonResponse);
use Mojo::JSON qw(true false);
use Data::Dumper;
use Carp qw(carp);

sub renderJsonResponse
{
	my ($c, $result, $err) = @_;

	if (ref $err eq 'ARRAY' )
	{
		my @real_err = grep {$_ if defined $_ } @$err;
		if ( @real_err > 0 )
		{
			$c->render(json => {error => true , error_message => join("\n", @real_err ) });
		}
		else
		{
			$c->render(json => {error => false , result => $result });
		}
	}
	elsif(ref $err eq '')
	{
		if ($err)
		{
			$c->render(json => {error => true, error_message => $err });
		}
		else
		{
			$c->render(json => {error => false , result => $result });
		}
	}

}

sub wrapMongoDBOp
{
	my ($collection, $err, $doc) = @_;
	if ($err)
	{
		carp $err;
	}
	return ($doc, $err);
}

sub wrapMangoOp
{
	my ($collection, $err, $doc) = @_;
	if ($err)
	{
		carp $err;
	}
	return $doc;
}

sub wrapUATX
{
	my ($ua, $tx) = @_;
	my $ret;
	if (my $res = $tx->success)
	{
		$ret = {error => false, result => $res->json };
	}
	else
	{
		my $err = $tx->error;
		my ($package, $file, $line) = caller;
		my $err_str = $err->{code} . ': '. $err->{message} .  " (at $file $line)";

		carp $err_str;
		$ret = {error => true, error_message => $err_str};
	}
	return $ret;
}

1;

